package com.southwind.springboottest.controller;

import com.southwind.springboottest.entity.BookCategory;
import com.southwind.springboottest.repository.BookCategoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.transaction.Transactional;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/bookCategory")
public class BookCategoryHandler {
    @Autowired
    private BookCategoryRepository bookCategoryRepository;

    @GetMapping("/findAll/{page}/{size}")
    public ResponseEntity<Map<String, Object>> findAll(
            @PathVariable("page") Integer page,
            @PathVariable("size") Integer size) {
        try {
            PageRequest request = PageRequest.of(page, size);
            Page<BookCategory> result = bookCategoryRepository.findAll(request);
            
            // 获取每个分类的图书数量
            List<Map<String, Object>> data = result.getContent().stream().map(category -> {
                Map<String, Object> item = new HashMap<>();
                item.put("category", category);
                item.put("bookCount", bookCategoryRepository.countBooksByCategory(category.getBookcaseid()));
                return item;
            }).collect(Collectors.toList());
            
            Map<String, Object> response = new HashMap<>();
            response.put("data", data);
            response.put("total", result.getTotalElements());
            response.put("page", page);
            response.put("size", size);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Collections.singletonMap("error", "服务器内部错误"));
        }
    }

    @PostMapping("/save")
    @Transactional
    public String save(@RequestBody BookCategory bookCategory){
        Integer maxId = bookCategoryRepository.findMaxBookcaseId();
        if(maxId == null) {
            bookCategory.setBookcaseid(1);
        } else {
            bookCategory.setBookcaseid(maxId + 1);
        }
        BookCategory result = bookCategoryRepository.save(bookCategory);
        return result != null ? "success" : "error";
    }

    @GetMapping("/findById/{id}")
    public BookCategory findById(@PathVariable("id") Integer id){
        return bookCategoryRepository.findById(id).get();
    }

    @PutMapping("/update")
    public String update(@RequestBody BookCategory bookCategory){
        BookCategory result = bookCategoryRepository.save(bookCategory);
        return result != null ? "success" : "error";
    }

    @DeleteMapping("/deleteById/{id}")
    public void deleteById(@PathVariable("id") Integer id){
        bookCategoryRepository.deleteById(id);
    }
}
